<!--
 * @Author: 栗佳琪 2745602478@qq.com
 * @Date: 2025-09-11 08:41:24
 * @LastEditors: 栗佳琪 2745602478@qq.com
 * @LastEditTime: 2025-09-17 09:36:00
 * @FilePath: \25-26学习\city\src\pages\components\bottom2.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <Title :title="title"></Title>

    <div ref="pieContainer" style="height: 75px;"></div>
    <div ref="columnContainer" style="height: 75px; margin-top: 20px;"></div>
  </div>
</template>

<script>
import { Pie, Column } from '@antv/g2plot';
import { each, groupBy } from '@antv/util';
import { mapState } from 'vuex';

export default {
  data() {
    return {
      title: '数据分类统计',
      // 原始数据
      originalData: [],
      // 饼图数据
      pieData: [],
      // 图表实例
      pieChart: null,
      columnChart: null
    }
  },
  computed: {
    ...mapState(['ed'])
  },
  watch: {
    ed: {
      handler(newVal) {
        // 根据设备信息重新查询数据
        if (newVal.engineer_id && newVal.device_id) {
          this.fetchData();
        }
      },
      deep: true
    }
  },
  methods: {
    // 初始化容器样式
    initContainerStyle() {
      insertCss(`
        .chart-container {
          display: flex;
          flex-direction: column !important;
          padding: 8px;
        }
        .pie-container, .column-container {
          flex: 1;
        }
      `);
    },
    // 获取数据
    async fetchData() {
      try {
        let response = await fetch('https://gw.alipayobjects.com/os/antfincdn/PC3daFYjNw/column-data.json', this.params);
        let data = await response.json();
        this.originalData = data;
        
        // 处理饼图数据
        let groupData = groupBy(data, 'type');
        let pieData = [];
        each(groupData, (values, k) => {
          pieData.push({ type: k, value: values.reduce((a, b) => a + b.value, 0) });
        });
        this.pieData = pieData;
        
        // 渲染图表
        this.renderCharts();
      } catch (error) {
        console.error('数据获取失败:', error);
      }
    },
    // 渲染图表
    renderCharts() {
      // 销毁旧图表实例
      if (this.pieChart) {
        this.pieChart.destroy();
      }
      if (this.columnChart) {
        this.columnChart.destroy();
      }
      
      // 渲染饼图
      this.pieChart = new Pie(this.$refs.pieContainer, {
        data: this.pieData,
        colorField: 'type',
        angleField: 'value',
        label: { type: 'inner' },
        tooltip: false,
        state: {
          active: {
            style: {
              lineWidth: 0,
            },
          },
        },
        interactions: [
          {
            type: 'element-highlight',
            cfg: {
              showEnable: [{ trigger: 'element:mouseenter', action: 'cursor:pointer' }],
              end: [
                { trigger: 'element:mouseleave', action: 'cursor:default' },
                { trigger: 'element:mouseleave', action: 'element-highlight:reset' },
              ],
            },
          },
        ],
      });
      
      // 渲染柱状图
      this.columnChart = new Column(this.$refs.columnContainer, {
        data: this.originalData,
        xField: 'city',
        yField: 'value',
        seriesField: 'type',
        isGroup: 'true',
        legend: false,
        columnStyle: {
          radius: [4, 4, 0, 0],
        },
      });
      
      // 渲染图表
      this.pieChart.render();
      this.columnChart.render();
      
      // 添加交互事件
      this.addChartInteractions();
    },
    // 添加图表交互
    addChartInteractions() {
      // 饼图鼠标悬停事件
      this.pieChart.on('element:mouseover', (evt) => {
        let eventData = evt.data;
        if (eventData?.data) {
          let type = eventData.data.type;
          this.columnChart.setState('selected', (datum) => datum.type === type);
          this.columnChart.setState('selected', (datum) => datum.type !== type, false);
        }
      });
      
      // 饼图鼠标离开事件
      this.pieChart.on('element:mouseleave', () => {
        this.columnChart.setState('selected', () => true, false);
      });
      
      // 饼图点击事件
      this.pieChart.on('element:click', (evt) => {
        let eventData = evt.data;
        if (eventData?.data) {
          let type = eventData.data.type;
          this.pieChart.changeData(this.pieData.filter((datum) => datum.type === type));
          this.columnChart.changeData(this.originalData.filter((datum) => datum.type === type));
        }
      });
      
      // 饼图双击事件
      this.pieChart.on('element:dblclick', () => {
        this.pieChart.changeData(this.pieData);
        this.columnChart.changeData(this.originalData);
      });
    }
  },
  async mounted() {
    await this.fetchData();

    this.initContainerStyle();
  },
  beforeDestroy() {
    // 组件销毁时销毁图表实例
    if (this.pieChart) {
      this.pieChart.destroy();
    }
    if (this.columnChart) {
      this.columnChart.destroy();
    }
  }
}
</script>

<style lang="less" scoped></style>